package com.jin.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.IService;
import com.jin.bean.Gate;
import com.jin.bean.Material;
import com.jin.bean.TruckRecord;
import com.jin.bean.Unit;
import com.jin.common.ResponseResult;
import com.jin.service.GateService;
import com.jin.service.MaterialService;
import com.jin.service.TruckRecordService;
import com.jin.service.UnitService;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * Created on 2025/2/24.
 * @author Zhongyuan Jin
 */
@RestController
@RequestMapping("/truck-record")
public class TruckRecordController {
    @Resource
    private TruckRecordService truckRecordService;

    @Resource
    private UnitService unitService;
    @ Resource
    private MaterialService materialService;

    @Resource
    private GateService gateService;

    //获取全部记录
    @GetMapping("/all")
    public ResponseResult<List<TruckRecord>> getAllMaterials() {
        List<TruckRecord> truckRecords = truckRecordService.list();
        return ResponseResult.success("获取全部记录", truckRecords);
    }

    //  按过滤条件查询（支持分页）
    @GetMapping("/list")
    @ResponseBody
    public Map<String, Object> list(
            @RequestParam(defaultValue = "1") int pageNum,
            @RequestParam(defaultValue = "10") int pageSize,
            @RequestParam(required = false) String gateName,
            @RequestParam(required = false) String plate,
            @RequestParam(required = false) String unitName,
            @RequestParam(required = false) @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") Date startTime,
            @RequestParam(required = false) @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") Date endTime) {

        Page<TruckRecord> page = new Page<>(pageNum, pageSize);
        Page<TruckRecord> truckRecordPage = truckRecordService.getTruckRecordsByConditions(gateName, plate, unitName, startTime, endTime, pageNum, pageSize);

        Map<String, Object> result = new HashMap<>();
        result.put("count", truckRecordPage.getTotal());
        result.put("data", truckRecordPage.getRecords());
        result.put("code", 200);
        result.put("totalWeight", calculateTotalWeight(truckRecordPage));
        result.put("totalVolume", calculateTotalVolume(truckRecordPage));
        return result;
    }

    //根据id获取记录
    @GetMapping("/{id}")
    public ResponseResult<TruckRecord> getById(@PathVariable Long id) {
        TruckRecord truckRecord = truckRecordService.getById(id);
        return ResponseResult.success("获取记录", truckRecord);
    }

    // 添加记录
    @PostMapping
    public ResponseResult<Boolean> add(@RequestBody TruckRecord truckRecord) {
        // 1. 获取名称
        String unitName = truckRecord.getUnitName();
        String materialName = truckRecord.getMaterialName();
        String gateName = truckRecord.getGateName();


        Unit unit = unitService.getOne(new QueryWrapper<Unit>().eq("unit_name", unitName));
        if (unit == null) {
            return ResponseResult.fail("未找到对应的施工单位：" + unitName);
        }

        // 3. 查询材料
        Material material = materialService.getOne(new QueryWrapper<Material>().eq("material_name", materialName));
        if (material == null) {
            return ResponseResult.fail("未找到对应的材料：" + materialName);
        }

        // 4. 查询门岗
        Gate gate = gateService.getOne(new QueryWrapper<Gate>().eq("gate_name", gateName));
        if (gate == null) {
            return ResponseResult.fail("未找到对应的门岗：" + gateName);
        }

        // 5. 设置ID
        truckRecord.setUnitId(unit.getId());
        truckRecord.setMaterialId(material.getId());
        truckRecord.setGateId(gate.getId());

        // 6. 保存记录
        boolean result = truckRecordService.save(truckRecord);
        return new ResponseResult<>(result ? 0 : 1, result ? "添加成功" : "添加失败", result, null);
    }

    // 更新记录
    @PutMapping("/{id}")
    public ResponseResult<Boolean> update(@PathVariable Long id, @RequestBody TruckRecord truckRecord) {
        System.out.println("*********"+truckRecord);
        System.out.println("*********"+id);
        try {
            truckRecord.setId(id);
            boolean result = truckRecordService.updateById(truckRecord);
            return ResponseResult.success("更新成功", result);
        } catch (Exception e) {
            return ResponseResult.fail("更新失败：" + e.getMessage());
        }
    }

    // 删除记录
    @DeleteMapping("/{id}")
    public ResponseResult<Boolean> delete(@PathVariable Long id) {
        try {
            boolean result = truckRecordService.removeById(id);
            return ResponseResult.success(result);
        } catch (IllegalArgumentException e) {
            return ResponseResult.fail(e.getMessage());
        } catch (Exception e) {
            return ResponseResult.fail("删除失败：" + e.getMessage());
        }
    }






    // 按单位ID查询（带分页）
    @GetMapping("/unit/{unitId}")
    @ResponseBody
    public Map<String, Object> getByUnitId(
            @PathVariable Integer unitId,
            @RequestParam(defaultValue = "1") int pageNum,
            @RequestParam(defaultValue = "10") int pageSize) {
        Page<TruckRecord> trucksPage = truckRecordService.getTruckRecordsByUnitId(unitId, pageNum, pageSize);
        Map<String, Object> result = new HashMap<>();
        result.put("count", trucksPage.getTotal());
        result.put("data", trucksPage.getRecords());
        result.put("totalWeight", calculateTotalWeight(trucksPage));
        result.put("totalVolume", calculateTotalVolume(trucksPage));
        result.put("code", 200);
        result.put("responseText", "查询成功");
        return result;
    }


    //  过滤条件导出 Excel
    @GetMapping("/export")
    public void exportWithConditions(
            @RequestParam(required = false) String gateName,
            @RequestParam(required = false) String plate,
            @RequestParam(required = false) String unitName,
            @RequestParam(required = false) @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") Date startTime,
            @RequestParam(required = false) @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") Date endTime
            , HttpServletResponse response) throws IOException {


        List<TruckRecord> truckRecords = truckRecordService.getTruckRecordsByConditionsForExport(gateName, plate, unitName, startTime, endTime);
        Workbook workbook = new XSSFWorkbook();

        Sheet sheet = workbook.createSheet("数据导出");
        int rowNum = 0;

        Row header = sheet.createRow(rowNum++);
        header.createCell(0).setCellValue("ID");
        header.createCell(1).setCellValue("门岗");
        header.createCell(2).setCellValue("施工单位");
        header.createCell(3).setCellValue("车牌号");
        header.createCell(4).setCellValue("时间");
        header.createCell(5).setCellValue("密度");
        header.createCell(6).setCellValue("体积");
        header.createCell(7).setCellValue("重量");
        header.createCell(8).setCellValue("扫描状态");
        header.createCell(9).setCellValue("同步状态");

        for (TruckRecord t : truckRecords) {
            Row row = sheet.createRow(rowNum++);
            row.createCell(0).setCellValue(t.getId());
            row.createCell(1).setCellValue(t.getGateName());
            row.createCell(2).setCellValue(t.getUnitName());
            row.createCell(3).setCellValue(t.getPlate());
            row.createCell(4).setCellValue(t.getTime());
            row.createCell(5).setCellValue(t.getDensity());
            row.createCell(6).setCellValue(t.getVolume());
            row.createCell(7).setCellValue(t.getWeight());
            row.createCell(8).setCellValue(t.getScanStatus() == 1 ? "已扫描" : "未扫描");
            row.createCell(9).setCellValue(t.getSyncStatus() == 1 ? "已同步" : "未同步");
        }

        // 动态生成文件名
        String timestamp = new SimpleDateFormat("yyyyMMddHHmmss").format(new Date());
        String filename = "车辆数据_" + timestamp + ".xlsx";

        // 使用 UTF-8 编码文件名，并按照 RFC 5987 标准设置 Content-Disposition
        String encodedFilename = URLEncoder.encode(filename, "UTF-8").replaceAll("\\+", "%20");

        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        response.setHeader("Content-Disposition", "attachment; filename=\"" + filename + "\"; filename*=UTF-8''" + encodedFilename);

        try (OutputStream os = response.getOutputStream()) {
            workbook.write(os);
        }
    }
    // 按单位ID导出（需要在前端进行后续处理）
    @GetMapping("/exportByUnit")
    public ResponseResult<List<TruckRecord>> exportAllByUnit(@RequestParam Integer unitId) {
        if (unitId == null) {
            return ResponseResult.fail("参数错误");
        }
        List<TruckRecord> truckRecords = truckRecordService.getTruckRecordsByUnitId(unitId, 1, Integer.MAX_VALUE).getRecords();
        return ResponseResult.success("获取成功", truckRecords);
    }

    // 按单位ID导出(在后端装配完成后发送，暂时不用)
    @GetMapping("/exportAllByUnit")
    public void exportByUnit(@RequestParam Integer unitId, HttpServletResponse response) throws IOException {
        List<TruckRecord> records = truckRecordService.getTruckRecordsByUnitId(unitId, 1, Integer.MAX_VALUE).getRecords();

        Workbook workbook = new XSSFWorkbook();
        Sheet sheet = workbook.createSheet("矿车载量信息");

        // 创建表头
        Row headerRow = sheet.createRow(0);
        String[] headers = {"序号", "唯一标识符", "门岗", "施工单位", "车牌号", "时间", "材料", "密度", "体积", "重量", "扫描状态", "同步状态"};
        for (int i = 0; i < headers.length; i++) {
            Cell cell = headerRow.createCell(i);
            cell.setCellValue(headers[i]);
        }

        // 填充数据
        int rowNum = 1;
        for (TruckRecord record : records) {
            Row row = sheet.createRow(rowNum++);
            row.createCell(0).setCellValue(record.getId().toString());
            row.createCell(1).setCellValue(record.getUuid());
            row.createCell(2).setCellValue(record.getGateName());
            row.createCell(3).setCellValue(record.getUnitName());
            row.createCell(4).setCellValue(record.getPlate());
            row.createCell(5).setCellValue(record.getTime().toLocaleString());
            row.createCell(6).setCellValue(record.getMaterialName());
            row.createCell(7).setCellValue(record.getDensity());
            row.createCell(8).setCellValue(record.getVolume());
            row.createCell(9).setCellValue(record.getWeight());
            row.createCell(10).setCellValue(record.getScanStatus() == 1 ? "已扫描" : "未扫描");
            row.createCell(11).setCellValue(record.getSyncStatus() == 1 ? "已同步" : "未同步");
        }

        // 设置响应头
        String filename = URLEncoder.encode("矿车载量信息_" + new Date(), "UTF-8");
        response.setHeader("Content-Disposition", "attachment; filename=" + filename + ".xlsx");
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");

        try (OutputStream os = response.getOutputStream()) {
            workbook.write(os);
        }
    }




    private double calculateTotalWeight(IPage<TruckRecord> page) {
        return Double.parseDouble(String.format("%.2f",
                page.getRecords().stream().mapToDouble(TruckRecord::getWeight).sum()));
    }

    private double calculateTotalVolume(IPage<TruckRecord> page) {
        return Double.parseDouble(String.format("%.2f",
                page.getRecords().stream().mapToDouble(TruckRecord::getVolume).sum()));
    }

}
